package com.ruoyi.capsule.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.capsule.service.LoginWxService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


@Service
public class LoginWxServiceImpl implements LoginWxService {
    @Autowired
    private ISysUserService userService;
    /**
     * 微信小程序登录
     *
     * @param code
     * @return
     */
    @Resource
    private AuthenticationManager authenticationManager;
    //引入redis
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private TokenService tokenService;

    public AjaxResult wxlogin(String code) {
        //请求微信登录的地址
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        String replaceUrl = url.replace("{0}", "wxe7bc7cbf8d335975").replace("{1}", "84682ecc09ffc0552022c0ee6825d390").replace("{2}", code); //替换为需要的值
        JSONObject jsonObject = JSONObject.parseObject(HttpUtils.sendGet(replaceUrl));    //转为json格式接收
//请求成功后 获取数据
        String openid = jsonObject.getString("openid");
        String nickname = jsonObject.getString("nickname");
        String session_key = jsonObject.getString("session_key");
        redisTemplate.opsForValue().set("openid", openid);
        if (openid == null) {
            return AjaxResult.error("登录失败");
        }
        //查询用户是否存在，用来判断是否为第一次登录，记住openId是每个用户的标识
        SysUser sysUser = userService.selectUserByUserName(openid);
        if (sysUser == null) {
            sysUser = new SysUser();
            sysUser.setUserName(openid);
            sysUser.setNickName("拾光胶囊");
            sysUser.setDeptId(3l);
            sysUser.setPassword(SecurityUtils.encryptPassword("123456"));

            userService.insertUser(sysUser);

            //获取登录用户的信息
            sysUser = userService.selectUserByUserName(openid);

//            LoginUser loginUser = new LoginUser();
//            loginUser.setUser(sysUser);
//            loginUser.setToken(session_key);

//            String token = tokenService.createToken(loginUser);
////
//            AjaxResult ajax = AjaxResult.success();
//            ajax.put("token",token);
//            ajax.put("userInfo", loginUser);

        }
        //更新
        //组装token信息  当前登录用户的信息
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(sysUser);
//            loginUser.setOpenId(openid);
        loginUser.setToken(session_key);

        //关键步骤 校验 顺便把用户登录信息存入redis供以后匹配用
        Authentication authentication = null;
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(openid, "123456");
        AuthenticationContextHolder.setContext(authenticationToken);
        // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
        authentication = authenticationManager.authenticate(authenticationToken);
        loginUser = (LoginUser) authentication.getPrincipal();



        String token = tokenService.createToken(loginUser);
        //
        AjaxResult ajax = AjaxResult.success();
//        ajax.put("token", token);
//        ajax.put("userInfo", loginUser);
            // 创建一个 HashMap 实例
            Map<String, String> tokenMap = new HashMap<>();
            // 将 token 存入 Map
            tokenMap.put("token", token);
            ajax.put("wxInfo",tokenMap);
            ajax.put("authInfo",tokenMap);

        return ajax;


    }

}
